import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { DatePipe } from '@angular/common';
import { CommonService } from '../../../services-common/common.service';
import { PermissionService } from '../../../service/permission.service';
import { GoodsLabelManageService } from '../goods-label-list/goods-label-manage.service';

@Component({
  selector: 'app-goods-label-edit',
  templateUrl: './goods-label-edit.component.html',
  styleUrls: ['./goods-label-edit.component.scss'],
  providers: [DatePipe]
})
export class GoodsLabelEditComponent implements OnInit {

  routeParams: any = {};
  formLabelWidth: string = '110px';
  formParams: any = {
    type: 1, // 类型 1.自定义 2.优惠券 3.直降促销
    businessId: '', // 关联ID
    weight: 0, // 权重 默认0
    name: '', // 标题
    remark: '', // 备注
    styleTag: '', // 样式 字典
    params: '', // 参数
    status: '', // 状态 1：启用 2：禁用
    getBeginTime: '', // 生效开始时间
    getEndTime: '', // 生效结束时间
    userType: '', // 适用用户 0：通用 1：C端 2：B端
    useScene: '', // 适用场景
    containsTypes: '', // 指定分类 0：全部 -1：全不选
    containsBrand: '', // 指定品牌 0：全部 -1：全不选
    containsGoods: '', // 包含商品
    filterGoods: '' // 排除商品
  };

  // 商品样式Options
  goodsStyleOptions: any = [];
  goodsStyleTips: string = '';

  // 生效日期
  takeEffectDates: any = [];

  // 适用场景options
  sceneOptions: any = [
    {value: 1, label: '列表页'},
    {value: 2, label: '详情页'},
    {value: 3, label: '购物车'},
    {value: 4, label: '结算页'}
  ];
  sceneSelected: any[] = [];

  // 指定分类Tree
  classifyTreeDatas: Array<any> = [];
  classifyAll: boolean = false;
  classifyTreeSelected: Array<number | string> = [];

  // 指定品牌options
  brandOptions: Array<any> = [];
  brandAll: boolean = false;
  brandSelected: Array<number | string> = [];

  classifyBrandNotAll: boolean = false;

  // 追加可用勾选
  appendGoodIds: any[] = [];
  // 排除可用勾选
  excludeGoodIds: any[] = [];

  /**
   * 选择商品 Modal
   * ---------------------------------------------------------------- 
   */
  selectGoodVisible = false;
  subSelectGoodLoading = false;
  selectGoodType: number = 0;
  selectGoodTable: any = {
    loading: false,
    name: '',
    tableData: [],
    page: 1,
    pageSize: 10,
    total: 0
  };
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();
  disabledCheckId: any = [];

  /**
   * 查看商品 Modal
   * ---------------------------------------------------------------- 
   */
  lookGoodsVisible = false;
  lookGoodsTable: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 10,
    total: 0
  };

  constructor(
    private message: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private commonService: CommonService,
    private datePipe: DatePipe,
    public permission: PermissionService,
    private services: GoodsLabelManageService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.loadGoodStyleData();
    this.loadClassifyTreeData();
    this.loadBrandOptionsData();
    this.loadGoodList();

    if (this.routeParams.id) {
      this.loadDetailsData();
    }
  }

  // load details
  async loadDetailsData() {
    await this.loadClassifyTreeData();

    let params = {
      id: this.routeParams.id
    }
    const messId = this.message.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const res: any = await this.services.getGoodsLabelDetailsData(params);
    this.message.remove(messId);

    if (res.code === 0) {
      const {data} = res || {};
      for (let key in this.formParams) {
        this.formParams[key] = !this.commonService.isEmpty(data[key]) ? data[key] : '';

        // 设置样式Tips
        if (key === 'styleTag') {
          this.styleChange(data.styleTag);
        }
      }

      // 生效时间
      this.takeEffectDates = [this.formParams.getBeginTime, this.formParams.getEndTime];

      // 适用场景
      this.sceneSelected = data.useScene ? data.useScene.split(',').map((m: any) => +m) : [];

      this.classifyBrandNotAll = data.containsBrand === '-1';
      // 指定分类
      this.classifyAll = data.containsTypes === '0';
      switch (data.containsTypes) {
        case '0':
          let temprrs: any = [];
          this.classifyTreeDatas.forEach((item: any) => {
            if (item.children && item.children.length) {
              item.children.forEach((tag: any) => {
                temprrs.push(tag.id);
              })
            }
          })
          this.classifyTreeSelected = temprrs;
          break;
        case '-1':
          this.classifyTreeSelected = [];
          break;
        default:
          this.classifyTreeSelected = data.containsTypes.split(',').map((m: any) => +m);
          break;
      }
      this.classifyTreeDatas.forEach((item: any) => {
        if (item.children && item.children.length) {
          item.children.forEach((tag: any) => {
            tag.checked = this.classifyTreeSelected.includes(tag.id);
          })
        }
      })

      // 指定品牌
      this.brandAll = data.containsBrand === '0';
      switch (data.containsBrand) {
        case '0':
          this.brandSelected = this.brandOptions.map(m => +m.id);
          break;
        case '-1':
          this.brandSelected = [];
          break;
        default:
          this.brandSelected = data.containsBrand.split(',').map((m: any) => +m);
          break;
      }
      
      // 追加可用
      this.appendGoodIds = (data.containsGoods && data.containsGoods !== '0') ? data.containsGoods.split(',').map((m: any) => +m) : [];
      // 排除可用
      this.excludeGoodIds = (data.filterGoods && data.filterGoods !== '0') ? data.filterGoods.split(',').map((m: any) => +m) : [];
    } else {
      this.message.error(res.message);
    }
  }

  // 查询商品样式options
  async loadGoodStyleData() {
    this.goodsStyleOptions = await this.commonService.getDictList('goods_tag_styles');
  }

  // 样式Change
  styleChange(val: any) {
    let tempObj: any = this.goodsStyleOptions.find((item: any) => item.content === val);
    this.goodsStyleTips = tempObj?.remark || '';
  }

  /**
   * ----------------------------------------------------------------
   * 使用商品 Check Box
   * ----------------------------------------------------------------
   */
  // 查询指定分类Tree
  async loadClassifyTreeData() {
    const res: any = await this.services.queryGoodsTypeTreeData();
    this.classifyTreeDatas = this.consversionTree(res.data);
  }

  consversionTree(arr: any) {
    return arr.map((item: any) => {
      if (item.children && item.children.length > 0) {
        item.children = this.consversionTree(item.children);
      }

      if (item.children && item.children.length <= 0) {
        item.checked = false;
      }

      let obj: any = {
        ...item,
        value: item.id,
        label: item.name
      }
      return obj
    })
  }

  // 查询指定品牌
  async loadBrandOptionsData() {
    const res: any = await this.services.queryGoodsBrandData();
    this.brandOptions = res?.data?.brandList || [];
  }

  // 指定分类全选
  classifyAllChange(val: boolean) {
    this.classifyTreeDatas.forEach((item: any) => {
      if (item.children && item.children.length) {
        item.children.forEach((tag: any) => {
          tag.checked = val;
        })
      }
    })
    
    this.updateSingleChecked();
    this.classifyAll = val;
    this.classifyBrandNotAll = false;
  }

  // 指定分类单选
  updateSingleChecked() {
    let tempArrs: any = [];
    let arrs: any = [];
    this.classifyTreeDatas.forEach((item: any) => {
      arrs = arrs.concat(item.children);
    })

    this.setClassifyIds(arrs, tempArrs);
    this.classifyTreeSelected = tempArrs.map((m: any) => +m.value);

    this.classifyAll = tempArrs.length === arrs.length;
    this.classifyBrandNotAll = false;
  }

  setClassifyIds(arr: Array<any>, checkArrs: Array<any>) {
    arr.forEach((item: any) => {
      if (item.checked) {
        checkArrs.push(item);
      }
    })
    return checkArrs;
  }

  // 指定品牌全选
  brandAllChange(val: boolean) {
    if (val) {
      this.brandSelected = this.brandOptions.map((m: any) => +m.value);
    } else {
      this.brandSelected = [];
    }

    this.brandAll = val;
    this.classifyBrandNotAll = false;
  }

  // 指定品牌单选
  brandSingCheckedChange() {
    this.classifyBrandNotAll = false;
    this.brandAll = this.brandSelected.length === this.brandOptions.length;
  }

  // 指定分类 or 指定品牌 全不选
  classifyNotAllChange(val: boolean) {
    if (val) {
      this.classifyTreeDatas.forEach((item: any) => {
        if (item.children && item.children.length) {
          item.children.forEach((tag: any) => {
            tag.checked = false;
          })
        }
      })
    }
    this.classifyTreeSelected = [];
    this.brandSelected = [];
    
    this.classifyAll = false;
    this.brandAll = false;
  }

  /**
   * ----------------------------------------------------------------
   * 选择商品Modal 勾选
   * ----------------------------------------------------------------
   */
  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.filter(tag => !this.disabledCheckId.includes(tag.id)).forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  /**
   * ----------------------------------------------------------------
   * 选择商品 Modal
   * ----------------------------------------------------------------
   */
  async loadGoodList() {
    let params = {
      name: this.selectGoodTable.name,
      current: this.selectGoodTable.page,
      size: this.selectGoodTable.pageSize
    }
    this.selectGoodTable.loading = true;
    const {code, data, message}: any = await this.services.getGoodsListData(params);
    this.selectGoodTable.loading = false;

    if (code === 0) {
      this.selectGoodTable.tableData = data.records || [];
      this.selectGoodTable.total = data.total || 0;
    } else {
      this.message.error(message);
    }
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.selectGoodTable.page = index;
    this.loadGoodList();
  }
  
  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.selectGoodTable.page = 1;
    this.selectGoodTable.pageSize = sizeNum;
    this.loadGoodList();
  }

  queryGoodsData() {
    this.selectGoodTable.page = 1;
    this.loadGoodList();
  }

  resetGoodsData() {
    this.selectGoodTable.name = '';
    this.selectGoodTable.page = 1;
    this.loadGoodList();
  }

  showGoodsMoreModal(type: number, disabledArr: any[]) {
    this.selectGoodType = type;
    this.setOfCheckedId.clear();
    this.disabledCheckId = disabledArr;
    this.setOfCheckedId = type === 1 ? new Set(this.appendGoodIds) : new Set(this.excludeGoodIds);

    this.selectGoodTable.name = '';
    this.selectGoodTable.page = 1;
    this.loadGoodList();
    this.selectGoodVisible = true;
  }

  subRelationGood() {
    if (!this.setOfCheckedId.size) {
      this.message.warning('请先选择所需关联商品');
      return
    }

    if (this.selectGoodType === 1) {
      this.appendGoodIds = [...this.setOfCheckedId];
    } else {
      this.excludeGoodIds = [...this.setOfCheckedId];
    }
    this.selectGoodVisible = false;
  }

  /**
   * ----------------------------------------------------------------
   * 查看商品 Modal
   * ----------------------------------------------------------------
   */
  async loadSelectedGoodTable() {
    let params = {
      idList: this.selectGoodType === 1 ? this.appendGoodIds : this.excludeGoodIds,
      pageNum: this.lookGoodsTable.page,
      pageSize: this.lookGoodsTable.pageSize
    }
    this.lookGoodsTable.loading = true;
    const {code, data, message}: any = await this.services.getSelectedGoodsList(params);
    this.lookGoodsTable.loading = false;

    if (code === 0) {
      this.lookGoodsTable.tableData = data?.records || [];
      this.lookGoodsTable.total = data?.total || 0;
    } else {
      this.message.error(message);
    }
  }

  // PageIndex Change
  onPageIndexChangeTwo(index: number) {
    this.lookGoodsTable.page = index;
    this.loadSelectedGoodTable();
  }
  
  // PageSize Change
  onPageSizeChangeTwo(sizeNum: number) {
    this.lookGoodsTable.page = 1;
    this.lookGoodsTable.pageSize = sizeNum;
    this.loadSelectedGoodTable();
  }

  showSelectedGoodModal(type: number) {
    this.selectGoodType = type;
    this.lookGoodsTable.page = 1;
    this.loadSelectedGoodTable();
    this.lookGoodsVisible = true;
  }

  deleteGoodItem(item: any) {
    let tempArrs = this.selectGoodType === 1 ? this.appendGoodIds : this.excludeGoodIds;
    let deleteIndex = tempArrs.findIndex(tag => tag.id === item.id);
    tempArrs.splice(deleteIndex, 1);
    this.loadSelectedGoodTable();
  }

  dateChange(result: any[], keys: string[]) {
    this.formParams[keys[0]] = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd HH:mm:ss') : '';
    this.formParams[keys[1]] = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd HH:mm:ss') : '';
  }

  /**
   * ----------------------------------------------------------------
   * submit form
   * ----------------------------------------------------------------
   */
  async submitForm() {
    if (!this.verifData()) {
      return
    }
    let params: any = {
      ...this.formParams,
      useScene: this.sceneSelected.join(','), // 适用场景
      containsTypes: this.classifyBrandNotAll ? '-1' : (this.classifyAll ? '0' : this.classifyTreeSelected.join(',')), // 指定分类
      containsBrand: this.classifyBrandNotAll ? '-1' : (this.brandAll ? '0' : this.brandSelected.join(',')), // 指定品牌
      containsGoods: this.appendGoodIds.length ? this.appendGoodIds.join(',') : '0', // 追加可用
      filterGoods: this.excludeGoodIds.length ? this.excludeGoodIds.join(',') : '0' // 排除可用
    }
    if (this.routeParams.id) {
      params.id = this.routeParams.id;
    }

    // return
    this.subSelectGoodLoading = true;
    const res: any = await this.services.addEditGoodsLabelData(params, this.routeParams.type);
    this.subSelectGoodLoading = false;
    if (res.code === 0) {
      this.message.success('保存成功');
      this.back();
    } else {
      this.message.error(res.message);
    }
  }

  verifData() {
    if (this.commonService.isEmpty(this.formParams.weight)) {
      this.message.warning('请输入权重');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.name)) {
      this.message.warning('请输入标题');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.styleTag)) {
      this.message.warning('请选择样式');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.status)) {
      this.message.warning('请选择状态');
      return false;
    } else if (!this.takeEffectDates.length) {
      this.message.warning('请选择生效时间');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.userType)) {
      this.message.warning('请选择适用用户');
      return false;
    } else if (!this.sceneSelected.length) {
      this.message.warning('请选择适用场景');
      return false;
    } else if (!this.classifyAll && !this.classifyBrandNotAll && !this.classifyTreeSelected.length) {
      this.message.warning('请选择指定分类');
      return false;
    } else if (!this.brandAll && !this.classifyBrandNotAll && !this.brandSelected.length) {
      this.message.warning('请选择指定品牌');
      return false;
    } else {
      return true;
    }
  }

  back() {
    history.back();
  }

  setDisabled(special?: string) {
    // str 'special'
    // 如果类型 = 自定义，则【所属业务、类型】这两项不允许编辑，其他都可以(等于都可编辑)
    // 如果类型 = 优惠券 / 直降促销，则【所属业务、类型、状态、生效时间、适用用户】不可以修改
    if (this.routeParams.id && [2, 3].includes(this.formParams.type) && special) {
      return true;
    }
    return false;
  }
}
